<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 标题 -->
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>

      <!-- 表单 -->
      <form @submit.prevent="handleSubmit">
        <!-- 用户名 -->
        <div class="form-item">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="formData.username"
            placeholder="请输入用户名"
            required
          />
        </div>

        <!-- 密码 -->
        <div class="form-item">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="formData.password"
            placeholder="请输入密码"
            required
          />
        </div>

        <!-- 注册时需要确认密码 -->
        <div class="form-item" v-if="!isLogin">
          <label for="confirmPassword">确认密码</label>
          <input
            type="password"
            id="confirmPassword"
            v-model="formData.confirmPassword"
            placeholder="请再次输入密码"
            required
          />
        </div>

        <!-- 身份选择 -->
        <div class="form-item">
          <label for="role">身份选择</label>
          <select id="role" v-model="formData.role" required>
            <option value="">请选择身份</option>
            <option value="admin" :disabled="!isLogin">管理员</option>
            <option value="user">用户</option>
            <option value="employee">员工</option>
          </select>
        </div>

        <!-- 提交按钮 -->
        <div class="form-item">
          <button type="submit">{{ isLogin ? '登录' : '注册' }}</button>
        </div>

        <!-- 切换登录/注册 -->
        <div class="switch-mode">
          <span @click="toggleMode">
            {{ isLogin ? '没有账号？点击注册' : '已有账号？点击登录' }}
          </span>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listUser, addUser } from '@/api/user'
import { listEmployee, addEmployee } from '@/api/employee'

const router = useRouter()
const isLogin = ref(true)

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: '',
})

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  // 切换模式时重置表单
  formData.username = ''
  formData.password = ''
  formData.confirmPassword = ''
  formData.role = ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证是否选择了身份
    if (!formData.role) {
      ElMessage.error('请选择身份')
      return
    }

    // 注册模式
    if (!isLogin.value) {
      // 验证两次密码是否一致
      if (formData.password !== formData.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
      }

      // 管理员不允许注册
      if (formData.role === 'admin') {
        ElMessage.error('管理员不允许注册')
        return
      }

      // 根据角色调用不同的注册API
      if (formData.role === 'user') {
        // 用户注册
        await addUser({
          username: formData.username,
          password: formData.password,
        })
      } else if (formData.role === 'employee') {
        // 员工注册
        await addEmployee({
          username: formData.username,
          password: formData.password,
          role: 1, // 员工角色为1
        })
      }

      ElMessage.success('注册成功，请登录')
      isLogin.value = true
      formData.password = ''
      formData.confirmPassword = ''
      return
    }

    // 登录模式
    let loginResult = null

    if (formData.role === 'user') {
      // 用户角色登录
      const params = {
        username: formData.username,
        password: formData.password,
      }
      const res = await listUser(params)
      loginResult = res.data
    } else if (formData.role === 'admin' || formData.role === 'employee') {
      // 管理员或员工角色登录
      const params = {
        username: formData.username,
        password: formData.password,
        role: formData.role === 'admin' ? 0 : 1, // 0为管理员，1为员工
      }
      const res = await listEmployee(params)
      loginResult = res.data
    }
    console.log(loginResult)
    // 验证登录结果
    if (loginResult && loginResult.length > 0) {
      // 登录成功，保存用户信息
      const userInfo = {
        username: formData.username,
        role: formData.role,
        ...loginResult[0],
      }
      console.log('存储用户信息')
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      console.log('登录成功')

      // 根据角色跳转到不同的首页
      ElMessage.success('登录成功')

      if (formData.role === 'user') {
        router.push('/user/home')
      } else if (formData.role === 'admin') {
        console.log('admin')
        router.push('/admin/medicine')
      } else if (formData.role === 'employee') {
        router.push('/employee/medicine')
      }
    } else {
      ElMessage.error('用户名或密码错误')
    }
  } catch (error) {
    console.error('操作失败：', error)
    ElMessage.error(error.message || '操作失败')
  }
}
</script>
